<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\home\controller;

use app\bwmall\model\shop\BwmallShopOrder;
use app\common\model\MemberPayment;
use buwang\base\BaseController;

use buwang\exception\CloudException;
use buwang\facade\CloudFacade;
use buwang\facade\Http;
use buwang\facade\Rpc;
use buwang\facade\WechatMp;
use buwang\facade\WechatPay;
use buwang\service\RedisLockService;
use encrypter\Encrypter;
use think\db\exception\PDOException;
use EasyWeChat\Kernel\Support;
use think\facade\Db;

class Index extends BaseController
{
    use \buwang\traits\JumpTrait;
    use \buwang\traits\JwtTrait;

    public function index()
    {
        return view();
//        $arr =Encrypter::bwEncode('/meme/diiek/index?app=999');
//        echo $arr.PHP_EOL;
//        echo Encrypter::bwDecode($arr);

//        $thumb = WechatMp::getWechatObj(4)->media->uploadVideo("/buwang/bwmall/public/upload/20201020/3e0dd5d0673f49d2b66ae65614dceb0a.mp4", "标题", "描述");
//        var_dump($thumb);die;

        //return $this->success('333');
//        $json = '{"appid":"wxaef25baa501eb9a0","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1522158841","nonce_str":"5f503f52469e2","openid":"ow53X5WCa_DhxicP3Js33EuimzJM","order_num":"wx159909459971572192","out_trade_no":"wx159909459971572192","result_code":"SUCCESS","return_code":"SUCCESS","time_end":"20200903085729","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200000694202009034930435501"}';
//        $sign = Support\generate_sign(json_decode($json, true), '7bfa551ed5384bcf4c4b2d0d911529f1');

        //var_dump($sign);die;//现在 821CE33B4A9E68BCF6125EF00781A7C5
//        try {
//            $res = CloudFacade::run('Ip', ['ip'=>'223.88.132.194']);
////        $res = CloudFacade::run('Idcard', ['idcard'=>'410322199408148918','realname'=>'聂冲冲']);
////        $res = CloudFacade::run('Sms', ['mobile'=>'17539592164','code'=>'2580']);
//        }catch (CloudException $e){
//            var_dump($e->getMessage());die;
//        }catch (PDOException $e){
//            var_dump($e->getMessage());die;
//        }
//        if(!$res) var_dump(CloudFacade::getError());
//        else var_dump($res);

        //      var_dump('ok');die;

//        hook('alismsSendHook', ['mobile'=>'17539592164', 'code'=>2580]);
//        var_dump($res);die;
        //return $this->error_jump('444','index/index');
        //var_dump('此刻位于 home/index/index');die;
        //dump(app()->getRootPath() . 'app/common/view/tpl/exception.tpl');
        //throw new ValidateException("出错了666666666");
        //Cookie::set('name', 'value', 3600);
        //session('myname1', 'thinkphp');
        //var_dump(Cookie::get('name'));die;
        //var_dump(session('myname'));die;
        //return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) 2020新春快乐</h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">14载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
    }

    public function hello($name = 'ThinkPHP6')
    {
        $data=Db::name('computer')->where('id', 8)->find();
        //有库存
        if ($data['num'] >0 ){
            //库存减一
            $res = Db::name('computer')->where('id', 8)->dec('num')->update();
            if ($res) {
                            dump('资源操作成功：');
                trace('资源操作成功：' . time(), 'error');
            }
        }

//        $processNum = 5000; //5万个进程
//        //表里id等于8的num数量为10
//        //5万进程抢10个数量
//        for ($i = 0; $i < $processNum; $i++) {
            //实例化
//            $redisLoke=new RedisLockService("jackhhy_key");
//            //获取redis锁
//            $locked=$redisLoke->Getlock();
//
//            if ($locked){
//                //获取锁成功
//                Db::startTrans();
//                try{
//                    $data=Db::name('computer')->where('id', 8)->lock(true)->find();
//                    //有库存
//                    if ($data['num'] >0 ){
//                        //库存减一
//                        $res = Db::name('computer')->where('id', 8)->dec('num')->update();
//                        if ($res) {
////                            dump('资源操作成功：');
//                            trace('资源操作成功：' . time(), 'error');
//                        }
//                    }
//                    Db::commit();
//                }catch (\Exception $exception){
//                    dump($exception->getMessage());
//                    Db::rollback();
//                }finally{
//                    //释放锁
//                    $redisLoke->Unlock();
//                }
//            }
//        }
    }

    public function http()
    {
        //$response = Http::get('https://www.baidu.com');
        //var_dump($response);
        //session('res', '$response->body()');
        file_put_contents('111.txt', time() . PHP_EOL, FILE_APPEND);
        Http::getAsync('https://api.wohuiliao.com', [], function (\http\Response $response) {
            sleep(5);
            echo '异步请求成功，响应内容：' . $response->body() . PHP_EOL;
            file_put_contents('111.txt', $response->body() . time() . PHP_EOL, FILE_APPEND);
        }, function (\http\RequestException $e) {
            echo '异步请求异常，错误码：' . $e->getCode() . '，错误信息：' . $e->getMessage() . PHP_EOL;
            session('res', '1211');
            file_put_contents('111.txt', '34343');
        });
        var_dump(file_get_contents('111.txt'));

        //echo json_encode(['code' => 200, 'msg' => '请求成功'], JSON_UNESCAPED_UNICODE) . PHP_EOL;


//        $obj = new Https();
//        $obj->asyncGet('https://api.wohuiliao.com/');


    }

    public function httpnew()
    {

        $promises = [
            Http::getAsync('https://api.wohuiliao.com'),
            Http::getAsync('https://api.wohuiliao.com', ['name' => 'gouguoyin']),
            Http::postAsync('https://www.baidu.com', ['name' => 'gouguoyin']),
        ];

        Http::concurrency(3)->multiAsync($promises, function (\http\Response $response, $index) {
            file_put_contents('222.txt', $index . '---' . $response->body() . time() . PHP_EOL, FILE_APPEND);

            echo "发起第 $index 个异步请求，请求时长：" . $response->json()->second . '秒' . PHP_EOL;
        }, function (\http\RequestException $e, $index) {
            echo "发起第 $index 个请求失败，失败原因：" . $e->getMessage() . PHP_EOL;
        });
        var_dump(file_get_contents('222.txt'));
    }

    public function data()
    {
        $data = ['key' => 'value'];
        //R()->code(403)->error('失败',$data,400009);
        R()->success($data);
    }

    public function send_rpc()
    {
        $serve = 'tcp://47.92.77.33:9600';
        $data = [
            'command' => 1,//1:请求,2:状态rpc 各个服务的状态
            'request' => [
                'serviceName' => 'common',
                'action' => 'mailBox',//行为名称
                'arg' => [
                    'args1' => 'args1',
                    'args2' => 'args2'
                ]
            ]
        ];

        Rpc::send($serve, $data, function (...$data) {
            var_dump($data);
        });
    }

}
